<template>
  <div>
    <el-card>
      <el-input disabled :value="$route.query.roleName"></el-input>
      <el-tree
        :data="data"
        show-checkbox
        ref="treeRef"
        node-key="id"
        default-expand-all
        :props="defaultProps"
      >
      </el-tree>
      <el-button :loading="loading" type="primary" @click="save"
        >保存</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </el-card>
  </div>
</template>

<script>
import roleApi from "@/api/acl/role";
import permissionApi from "@/api/acl/permission";

export default {
  data() {
    return {
      loading: false,
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      checkedArr: [],
    };
  },

  methods: {
    // 保存按钮
    async save() {
      const arr = this.$refs.treeRef?.getCheckedKeys();
      const str = arr.join(",");
      await permissionApi.doAssign(this.$route.query.id, str);
      this.$router.replace("/rules/roleControl");
    },

    // 取消按钮
    cancel() {
      this.$router.replace("/rules/roleControl");
    },

    // 获取数据
    async getAssign() {
      const result = await permissionApi.toAssign(this.$route.query.id);
      this.data = result.data.children;
      const checked = this.getCheckedIds(result.data.children);
      this.$refs.treeRef?.setCheckedKeys(checked);
      this.checkedArr = [];
    },

    // 获取所有已选中的项
    getCheckedIds(addAssign) {
      // addAssign是获取的总数据, 对它执行foreach
      addAssign.forEach((item) => {
        // 如果item.select为true, 且为第四级, 就将本项的id传入initArr数组
        if (item.select && item.level === 4) {
          this.checkedArr.push(item.id);
          // 当本项依旧拥有children时, 递归
        } else if (item.children) {
          this.getCheckedIds(item.children, this.checkedArr);
        }
      });
      return this.checkedArr;
    },
  },

  mounted() {
    this.getAssign();
  },
};
</script>

<style lang="scss" scoped></style>
